package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.adapter.UserAdapter;
import com.example.mydy.api.ApiClient;
import com.example.mydy.model.UserData;
import com.example.mydy.model.UserInfo;
import com.example.mydy.model.UserListResponse;
import com.example.mydy.model.User;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.model.RewardTask;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.mydy.api.UserApi;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.SharedPreferencesManager;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

public class UserManagementActivity extends AppCompatActivity implements View.OnClickListener, UserAdapter.OnUserActionListener {

    private static final String TAG = "UserManagementActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_TOKEN = "token";

    private Toolbar toolbar;
    private EditText searchEditText;
    private Button searchButton;
    private TextView userStatusTextView;
    private Spinner userLevelSpinner;
    private TextView userCountTextView;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private FloatingActionButton fabAddUser;
    private ProgressBar progressBar;

    private UserAdapter adapter;
    private List<UserInfo> userList = new ArrayList<>();
    private String currentLevel = "全部";

    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_management);

        try {
            initViews();
            initUserApi();
            setupRecyclerView();
            setupSwipeRefresh();
            setClickListeners();
            loadUsers();
        } catch (Exception e) {
            Log.e(TAG, "初始化失败: " + e.getMessage(), e);
            Toast.makeText(this, "初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar_user_management);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        
        // 设置返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> {
            finish();
        });
        
        // 设置刷新按钮
        findViewById(R.id.btn_refresh).setOnClickListener(v -> {
            loadUsers();
        });
        
        searchEditText = findViewById(R.id.et_search_user);
        searchButton = findViewById(R.id.btn_search_user);
        userStatusTextView = findViewById(R.id.tv_user_status);
        userLevelSpinner = findViewById(R.id.spinner_user_level);
        userCountTextView = findViewById(R.id.tv_user_count);
        recyclerView = findViewById(R.id.rv_users);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_users);
        fabAddUser = findViewById(R.id.fab_add_user);
        progressBar = findViewById(R.id.progress_bar);
    }

    private void initUserApi() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiClient.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        userApi = retrofit.create(UserApi.class);
    }

    private void setupSwipeRefresh() {
        swipeRefreshLayout.setOnRefreshListener(this::loadUsers);
    }

    private void setupRecyclerView() {
        adapter = new UserAdapter(this, userList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    private void setClickListeners() {
        searchButton.setOnClickListener(this);
        fabAddUser.setOnClickListener(this);
        
        userLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentLevel = parent.getItemAtPosition(position).toString();
                loadUsers();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_search_user) {
            searchUsers();
        } else if (v.getId() == R.id.fab_add_user) {
            showAddUserDialog();
        } else if (v.getId() == R.id.btn_refresh) {
            loadUsers();
        }
    }

    private void searchUsers() {
        String keyword = searchEditText.getText().toString().trim();
        if (keyword.isEmpty()) {
            loadUsers();
            return;
        }
        
        // TODO: 实现搜索用户功能
        Toast.makeText(this, "搜索用户功能开发中", Toast.LENGTH_SHORT).show();
    }

    private void loadUsers() {
        if (progressBar != null) {
        progressBar.setVisibility(View.VISIBLE);
        }
        
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
        
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "未登录，使用离线模式", Toast.LENGTH_SHORT).show();
            loadFallbackData();
            return;
        }
        
        // 在线模式加载用户数据
        Call<CommonResponse> call = userApi.getAllUsers("Bearer " + token);
        call.enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (progressBar != null) {
                progressBar.setVisibility(View.GONE);
                }
                
                if (swipeRefreshLayout != null) {
                    swipeRefreshLayout.setRefreshing(false);
                }
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        try {
                            List<UserInfo> users = new ArrayList<>();
                            Object data = response.body().getData();
                            
                            if (data instanceof List) {
                                for (Object item : (List) data) {
                                    if (item instanceof Map) {
                                        Map<String, Object> map = (Map<String, Object>) item;
                                        int id = ((Double) map.getOrDefault("id", 0.0)).intValue();
                                        String username = (String) map.getOrDefault("username", "");
                                        String nickname = (String) map.getOrDefault("nickname", "");
                                        String phone = (String) map.getOrDefault("phone", "");
                                        double balance = ((Double) map.getOrDefault("balance", 0.0));
                                        int points = ((Double) map.getOrDefault("points", 0.0)).intValue();
                                        String level = (String) map.getOrDefault("level", "普通");
                                        String status = (String) map.getOrDefault("status", "正常");
                                        String createdAt = (String) map.getOrDefault("createdAt", "");
                                        
                                        UserInfo user = new UserInfo();
                                        user.setId(id);
                                        user.setUsername(username);
                                        user.setNickname(nickname);
                                        user.setPhone(phone);
                                        user.setBalance(balance);
                                        user.setPoints(points);
                                        user.setLevel(level);
                                        user.setStatus(status);
                                        user.setCreatedAt(createdAt);
                                        users.add(user);
                                    }
                                }
                                
                                userList.clear();
                                userList.addAll(users);
                                adapter.notifyDataSetChanged();
                                
                                if (userCountTextView != null) {
                                    userCountTextView.setText("总用户数: " + userList.size());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(UserManagementActivity.this, "解析数据出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        String message = response.body().getMessage();
                        Toast.makeText(UserManagementActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(UserManagementActivity.this, "请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    loadFallbackData();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (progressBar != null) {
                progressBar.setVisibility(View.GONE);
                }
                
                if (swipeRefreshLayout != null) {
                    swipeRefreshLayout.setRefreshing(false);
                }
                
                Toast.makeText(UserManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                t.printStackTrace();
                loadFallbackData();
            }
        });
    }
    
    private void loadFallbackData() {
        // 清空用户列表
        userList.clear();
        adapter.notifyDataSetChanged();
        
        // 显示空数据视图
        if (userList.isEmpty()) {
            if (recyclerView.getVisibility() == View.VISIBLE) {
                recyclerView.setVisibility(View.GONE);
            }
        }
        
        // 向用户显示错误信息
        Toast.makeText(this, "无法从服务器加载用户数据，请检查网络连接", Toast.LENGTH_LONG).show();
        Log.e(TAG, "无法从服务器加载用户数据");
        
        // 更新界面状态
        progressBar.setVisibility(View.GONE);
        swipeRefreshLayout.setRefreshing(false);
        updateUserCountText();
    }

    private void updateUserListUI() {
        adapter.notifyDataSetChanged();
        
        if (userCountTextView != null) {
            userCountTextView.setText("共 " + userList.size() + " 名用户");
        }
    }

    private void updateUser(int userId, Map<String, Object> userData) {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        userApi.updateUser("Bearer " + token, userId, userData).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(UserManagementActivity.this, "用户信息更新成功", Toast.LENGTH_SHORT).show();
                        for (int i = 0; i < userList.size(); i++) {
                            if (userList.get(i).getId() == userId) {
                                UserInfo user = userList.get(i);
                                if (userData.containsKey("nickname")) {
                                    user.setNickname((String) userData.get("nickname"));
                                }
                                if (userData.containsKey("phone")) {
                                    user.setPhone((String) userData.get("phone"));
                                }
                                if (userData.containsKey("level")) {
                                    user.setLevel((String) userData.get("level"));
                                }
                                adapter.notifyItemChanged(i);
                                break;
                            }
                        }
                    } else {
                        Toast.makeText(UserManagementActivity.this, "更新失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(UserManagementActivity.this, "更新失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(UserManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void updatePassword(int userId, String newPassword) {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Map<String, Object> passwordData = new HashMap<>();
        passwordData.put("password", newPassword);

        Call<CommonResponse> call = userApi.updatePassword("Bearer " + token, passwordData);

        call.enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    CommonResponse commonResponse = response.body();
                    if (commonResponse.isSuccess()) {
                        Toast.makeText(UserManagementActivity.this, "密码更新成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(UserManagementActivity.this, commonResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(UserManagementActivity.this, "密码更新失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(UserManagementActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void updateUserAndPassword(int userId, Map<String, Object> userData) {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Call<CommonResponse> call = userApi.updateUserAndPassword(userId, userData);

        call.enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    CommonResponse commonResponse = response.body();
                    if (commonResponse.isSuccess()) {
                        Toast.makeText(UserManagementActivity.this, "用户信息更新成功", Toast.LENGTH_SHORT).show();
                        loadUsers();
                    } else {
                        Toast.makeText(UserManagementActivity.this, commonResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(UserManagementActivity.this, "用户信息更新失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(UserManagementActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getTokenFromSharedPreferences() {
        SharedPreferences sharedPreferences = getSharedPreferences("MyAppPrefs", MODE_PRIVATE);
        return sharedPreferences.getString("token", "");
    }

    public static class EditUserDialogFragment extends DialogFragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.dialog_edit_user, container, false);
            final EditText usernameEdit = view.findViewById(R.id.username_edit);
            final EditText phoneEdit = view.findViewById(R.id.phone_edit);
            final Spinner spinnerLevel = view.findViewById(R.id.spinner_user_level);
            final EditText balanceEdit = view.findViewById(R.id.balance_edit);
            final EditText passwordEdit = view.findViewById(R.id.password_edit);
            Button saveButton = view.findViewById(R.id.btn_save);

            final int userId = getArguments().getInt("userId");
            usernameEdit.setText(getArguments().getString("username"));
            phoneEdit.setText(getArguments().getString("phone"));
            
            String userLevel = getArguments().getString("level");
            for (int i = 0; i < spinnerLevel.getAdapter().getCount(); i++) {
                if (spinnerLevel.getAdapter().getItem(i).toString().equals(userLevel)) {
                    spinnerLevel.setSelection(i);
                    break;
                }
            }
            
            balanceEdit.setText(String.valueOf(getArguments().getDouble("balance")));

            saveButton.setOnClickListener(v -> {
                Map<String, Object> userData = new HashMap<>();
                String username = usernameEdit.getText().toString().trim();
                String phone = phoneEdit.getText().toString().trim();
                String level = spinnerLevel.getSelectedItem().toString();
                String balanceStr = balanceEdit.getText().toString().trim();
                String password = passwordEdit.getText().toString().trim();

                if (!username.isEmpty()) userData.put("username", username);
                if (!phone.isEmpty()) userData.put("phone", phone);
                if (!level.isEmpty() && !"全部".equals(level)) userData.put("level", level);
                if (!balanceStr.isEmpty()) {
                    try {
                        double balance = Double.parseDouble(balanceStr);
                        userData.put("balance", balance);
                    } catch (NumberFormatException e) {
                        Toast.makeText(getActivity(), "余额输入格式错误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!password.isEmpty()) {
                    if (password.length() < 6) {
                        Toast.makeText(getActivity(), "密码需为6位以上", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    userData.put("password", password);
                }

                if (userData.isEmpty()) {
                    Toast.makeText(getActivity(), "请至少输入一个要修改的信息", Toast.LENGTH_SHORT).show();
                    return;
                }

                ((UserManagementActivity) getActivity()).updateUserAndPassword(userId, userData);
                dismiss();
            });

            return view;
        }
    }

    private void showAddUserDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_edit_user, null);
        builder.setView(view);
        
        TextView tvTitle = view.findViewById(R.id.dialog_title);
        tvTitle.setText("添加用户");
        
        EditText etUsername = view.findViewById(R.id.username_edit);
        EditText etNickname = view.findViewById(R.id.nickname_edit);
        EditText etPhone = view.findViewById(R.id.phone_edit);
        EditText etInviter = view.findViewById(R.id.inviter_edit);
        Spinner spinnerLevel = view.findViewById(R.id.spinner_user_level);
        EditText etBalance = view.findViewById(R.id.balance_edit);
        EditText etPassword = view.findViewById(R.id.password_edit);

        builder.setPositiveButton("添加", (dialog, which) -> {
                    String username = etUsername.getText().toString().trim();
                    String nickname = etNickname.getText().toString().trim();
                    String phone = etPhone.getText().toString().trim();
                    String inviter = etInviter.getText().toString().trim();
                    String level = spinnerLevel.getSelectedItem().toString();
                    String balanceStr = etBalance.getText().toString().trim();
                    String password = etPassword.getText().toString().trim();
                    
                    if (TextUtils.isEmpty(username)) {
                        Toast.makeText(UserManagementActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    if (TextUtils.isEmpty(password)) {
                        Toast.makeText(UserManagementActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    double balance = 0.0;
                    try {
                        if (!TextUtils.isEmpty(balanceStr)) {
                            balance = Double.parseDouble(balanceStr);
                        }
                        } catch (NumberFormatException e) {
                        Toast.makeText(UserManagementActivity.this, "余额必须是数字", Toast.LENGTH_SHORT).show();
                            return;
                    }
                    
                        UserInfo newUser = new UserInfo();
                        newUser.setUsername(username);
                    newUser.setNickname(nickname);
                        newUser.setPhone(phone);
                    newUser.setBalance(String.valueOf(balance));
                    newUser.setLevel(level.equals("全部") ? "普通" : level);
                    
                    if (NetworkUtils.USE_OFFLINE_MODE) {
                        UserData userData = new UserData();
                        userData.setId(userList.size() + 1);
                        userData.setUsername(username);
                        userData.setNickname(nickname);
                        userData.setPhone(phone);
                        userData.setBalance(balance);
                        userData.setLevel(level.equals("全部") ? "普通" : level);
                        
                        if (!TextUtils.isEmpty(inviter)) {
                            userData.setInviter(inviter);
                        }
                        
                        boolean success = MockDataManager.getInstance().updateUser(newUser);
                        if (success) {
                            Toast.makeText(UserManagementActivity.this, "用户添加成功", Toast.LENGTH_SHORT).show();
                            loadFallbackData();
                        } else {
                            Toast.makeText(UserManagementActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                        }
                        return;
                    }
                    
                    Map<String, Object> userData = new HashMap<>();
                    userData.put("username", username);
                    userData.put("nickname", nickname);
                        userData.put("phone", phone);
                    userData.put("level", level.equals("全部") ? "普通" : level);
                    userData.put("balance", balance);
                    userData.put("password", password);
                    
                    if (!TextUtils.isEmpty(inviter)) {
                        userData.put("inviter", inviter);
                    }
                    
                    String token = NetworkUtils.getAuthToken();
                    userApi.createUser("Bearer " + token, userData).enqueue(new Callback<CommonResponse>() {
                        @Override
                        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                if (response.body().isSuccess()) {
                                    Toast.makeText(UserManagementActivity.this, "用户添加成功", Toast.LENGTH_SHORT).show();
                                    loadUsers();
                                } else {
                                    Toast.makeText(UserManagementActivity.this, 
                                            "添加失败: " + response.body().getMessage(), 
                                            Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(UserManagementActivity.this, 
                                        "添加失败，错误码: " + response.code(), 
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                        
                        @Override
                        public void onFailure(Call<CommonResponse> call, Throwable t) {
                            Toast.makeText(UserManagementActivity.this, 
                                    "网络错误: " + t.getMessage(), 
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                })
                .setNegativeButton("取消", null);
        
        AlertDialog dialog = builder.create();
        dialog.show();
        
        Button btnSave = view.findViewById(R.id.btn_save);
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        
        btnSave.setOnClickListener(v -> {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
        });
        
        btnCancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
    }
    
    private void showEditUserDialog(UserInfo userInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_edit_user, null);
        builder.setView(view);
        
        EditText etUsername = view.findViewById(R.id.username_edit);
        EditText etNickname = view.findViewById(R.id.nickname_edit);
        EditText etPhone = view.findViewById(R.id.phone_edit);
        EditText etInviter = view.findViewById(R.id.inviter_edit);
        Spinner spinnerLevel = view.findViewById(R.id.spinner_user_level);
        EditText etBalance = view.findViewById(R.id.balance_edit);
        EditText etPassword = view.findViewById(R.id.password_edit);
        
        etUsername.setText(userInfo.getUsername());
        etNickname.setText(userInfo.getNickname());
        etPhone.setText(userInfo.getPhone());
        etBalance.setText(userInfo.getBalance());
        
        if (userInfo.getInviter() != null) {
            etInviter.setText(userInfo.getInviter());
        }

        String userLevel = userInfo.getLevel();
        for (int i = 0; i < spinnerLevel.getAdapter().getCount(); i++) {
            if (spinnerLevel.getAdapter().getItem(i).toString().equals(userLevel)) {
                spinnerLevel.setSelection(i);
                break;
            }
        }

        builder.setTitle("编辑用户")
                .setPositiveButton("保存", (dialog, which) -> {
                    String username = etUsername.getText().toString().trim();
                    String nickname = etNickname.getText().toString().trim();
                    String phone = etPhone.getText().toString().trim();
                    String inviter = etInviter.getText().toString().trim();
                    String level = spinnerLevel.getSelectedItem().toString();
                    String balanceStr = etBalance.getText().toString().trim();
                    String password = etPassword.getText().toString().trim();
                    
                    if (TextUtils.isEmpty(username)) {
                        Toast.makeText(UserManagementActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    double balance = 0.0;
                        try {
                        if (!TextUtils.isEmpty(balanceStr)) {
                            balance = Double.parseDouble(balanceStr);
                        }
                        } catch (NumberFormatException e) {
                            Toast.makeText(UserManagementActivity.this, "余额必须是数字", Toast.LENGTH_SHORT).show();
                            return;
                    }
                    
                    // 构建更新用户信息的数据
                    Map<String, Object> userData = new HashMap<>();
                    userData.put("username", username);
                    userData.put("nickname", nickname);
                    if (!TextUtils.isEmpty(phone)) {
                        userData.put("phone", phone);
                    }
                    // 设置邀请人
                    if (!TextUtils.isEmpty(inviter)) {
                        userData.put("inviter", inviter);
                    }
                    // 如果等级不是"全部"，则更新等级
                    if (!"全部".equals(level)) {
                        userData.put("level", level);
                    }
                    if (!TextUtils.isEmpty(balanceStr)) {
                        userData.put("balance", balance);
                    }
                    if (!TextUtils.isEmpty(password)) {
                        userData.put("password", password);
                    }
                    
                    // 更新用户信息
                    updateUser(userInfo.getId(), userData);
                })
                .setNegativeButton("取消", null);
        
        AlertDialog dialog = builder.create();
        dialog.show();
        
        // 获取对话框按钮，并手动设置监听器
        Button btnSave = view.findViewById(R.id.btn_save);
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        
        btnSave.setOnClickListener(v -> {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
        });
        
        btnCancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
    }

    @Override
    public void onEditUser(UserInfo user) {
        showEditUserDialog(user);
    }

    @Override
    public void onDeleteUser(UserInfo user) {
        showDeleteConfirmationDialog(user);
    }

    @Override
    public void onViewTasks(UserInfo user) {
        showUserTasksDialog(user);
    }

    private void showDeleteConfirmationDialog(UserInfo user) {
        new AlertDialog.Builder(this)
                .setTitle("删除用户")
                .setMessage("确定要删除用户 " + user.getUsername() + " 吗？此操作不可恢复。")
                .setPositiveButton("删除", (dialog, which) -> deleteUser(user.getId()))
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteUser(long userId) {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "未登录，无法删除用户", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Call<CommonResponse> call = userApi.deleteUserById("Bearer " + token, (int)userId);
        call.enqueue(new Callback<CommonResponse>() {
                        @Override
                        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                if (response.body().isSuccess()) {
                        Toast.makeText(UserManagementActivity.this, "用户删除成功", Toast.LENGTH_SHORT).show();
                        loadUsers();
                                } else {
                        String message = response.body().getMessage();
                        Toast.makeText(UserManagementActivity.this, message, Toast.LENGTH_SHORT).show();
                                }
                            } else {
                    Toast.makeText(UserManagementActivity.this, "删除失败: " + response.code(), Toast.LENGTH_SHORT).show();
                            }
                        }
                        
                        @Override
                        public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(UserManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                t.printStackTrace();
            }
        });
    }

    private void showUserTasksDialog(UserInfo user) {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }
        
        userApi.getUserRewardTasks("Bearer " + token, user.getId()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(UserManagementActivity.this, "在线模式暂未实现此功能", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UserManagementActivity.this, "获取用户任务失败", Toast.LENGTH_SHORT).show();
                }
            }
            
            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                Toast.makeText(UserManagementActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private class UserTasksAdapter extends RecyclerView.Adapter<UserTasksAdapter.ViewHolder> {
        private List<RewardTask> taskList;
        
        UserTasksAdapter(List<RewardTask> taskList) {
            this.taskList = taskList;
        }
        
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(UserManagementActivity.this).inflate(R.layout.item_user_task, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            RewardTask task = taskList.get(position);
            holder.tvTaskTitle.setText(task.getTitle());
            holder.tvTaskDescription.setText(task.getDescription());
            holder.tvTaskReward.setText("奖励: " + task.getReward() + "元");
            holder.tvTaskStatus.setText(task.isTaken() ? "已接取" : "未接取");
        }
        
        @Override
        public int getItemCount() {
            return taskList.size();
        }
        
        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvTaskTitle, tvTaskDescription, tvTaskReward, tvTaskStatus;
            
            ViewHolder(@NonNull View itemView) {
                super(itemView);
                tvTaskTitle = itemView.findViewById(R.id.tv_task_title);
                tvTaskDescription = itemView.findViewById(R.id.tv_task_description);
                tvTaskReward = itemView.findViewById(R.id.tv_task_reward);
                tvTaskStatus = itemView.findViewById(R.id.tv_task_status);
            }
        }
    }

    private void refreshUserList() {
        loadUsers();
    }
}